from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from myadmin.models import Users
from myadmin import upload
from django.contrib.auth.hashers import make_password, check_password
import os
from django.db.models import Q
from django.core.paginator import Paginator
# Create your views here.

#登录页面
def login(request):
    return render(request,'admin/login.html')

    # 也可以把下面dologin的操作卸载login函数里面,增加判断:如果是get请求,说明是访问后台
    #  入股哦是post方式,说明是登录表单提交
    #
    # if request.method == get:
    #     return render(request,'admin/login.html')
    # elif requests.method == post:
    #     pass 下面的代码放这里
    #

#登录操作验证
def dologin(request):
    # 先判断验证码是否输入正确
    if request.session['verifycode'] != request.POST['vcode']:
        return HttpResponse('<script>alert("验证码输入有误");location.href="/admin/login"</script>')
    # 判断用户是否存在

    # 用try的好处是:ob如果获取不到,逻辑上说明输入错误,可以防止集合查询获取不到报错.
    try:
        ob = Users.objects.get(username=request.POST.get('username'))
        print(ob)
        if ob:
            # 判断密码是否正确
            if check_password(request.POST['password'],ob.password):
                print('1111111111111111111111')
                # 密码正确 判断权限是不是超管
                if ob.status == 2:
                    # 把用户数据放入session并且跳转到后台首页.
                    request.session['adminuser'] = {'username':ob.username,'pic':ob.picurl}
                    return HttpResponse('<script>alert("登录成功");location.href="/admin"</script>')
        # 我们不希望在这里做else给用户提示,所以else的暂时不需要.
                else:
                    return HttpResponse('<script>alert("用户名或密码有误");location.href="/admin/login"</script>')
            else:
                return HttpResponse('<script>alert("用户名或密码有误");location.href="/admin/login"</script>')
    except:
        return HttpResponse('<script>alert("用户名或密码有误");location.href="/admin/login"</script>')



# 退出登录操作
def loginout(requets):
    # 我们验证登录靠的是session['adminuser'] 的数据,删除这一项.然后跳转到登录页面
    del requets.session['adminuser']
    return HttpResponse('<script>alert("退出成功");location.href="/admin/login"</script>')
# 登录退出,虽然成功了,但是我们不用登录也能进入后台首页,后面就需要中间件进行控制了.


def index(request):
    return render(request,'admin/index.html')



# 以下都是会员用户管理操作:useradd uinsert ulist uedit usave udel

def useradd(request):

    return render(request,'admin/user/add.html')

def uinsert(request):
    try:
        # print(request.POST)
        obj = Users()
        obj.username = request.POST.get('username')
        obj.age = int(request.POST.get('age'))
        obj.email = request.POST.get('email')
        #密码加密
        obj.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        obj.phone = request.POST.get('phone')
        obj.sex = request.POST.get('sex')
        # 执行图片上传
        myfile = request.FILES.get('pic')
        # 如果有图片,就上传
        if myfile:
            newurl = upload.uploadimg(myfile)
            print(newurl)
            # 数据库
            obj.picurl = newurl
    # 没有图片,就用默认值
        else:
            obj.picurl = 'default/default.jpg'
        obj.save()
        return HttpResponse('<script>alert("添加成功");location.href="{}"</script>'.format(reverse('user_list')))
    except:
        return HttpResponse('<script>alert("添加失败");location.href="{}"</script>'.format(reverse('user_add')))

def ulist(request):
    types = request.GET.get('types',None)
    keywords = request.GET.get('keywords','')
    # print(types,keywords)
    #static 对应关键字
    staticdict = {'正常':0,'禁用':1}
    #如果有搜神条件
    if types:
        #全部搜索
        if types == 'all':
            db = Users.objects.filter(Q(username__contains=keywords)
                                      |Q(email__contains=keywords)
                                      |Q(phone__contains=keywords)
                                      |Q(age__contains=keywords)
                                      |Q(sex__contains=keywords)
                                      |Q(status__contains=keywords)
                                      ).order_by('-addtime')
        # 逐个搜索
        elif types =='username':
            db = Users.objects.filter(username__contains=keywords).order_by('-addtime')
        elif types =='email':
            db = Users.objects.filter(email__contains=keywords).order_by('-addtime')
        elif types =='phone':
            db = Users.objects.filter(phone__contains=keywords).order_by('-addtime')
        elif types =='age':
            db = Users.objects.filter(age__contains=keywords).order_by('-addtime')
        elif types =='sex':
            db = Users.objects.filter(sex__contains=keywords).order_by('-addtime')
        elif types =='status':
            db = Users.objects.filter(status__contains=staticdict.get(keywords,'111')).order_by('-addtime')

    #如果没有搜神条件
    else:
        db = Users.objects.exclude(status=3).order_by('-addtime')


    #对以上操作获取的数据db做分页展示,需要引入分页类
    pageobj = Paginator(db,8)  #实例化分页对象
    # print(pageobj)
    p = int(request.GET.get('p',1)) #a标签p传参
    pdata = pageobj.page(p)   #当前页数据
    # print(pdata)
    pagelist = pageobj.page_range   #页码列表
    pageallnum = pageobj.num_pages   #直接分页对象获取总页数
    # pageallnum = pdata.paginator.num_pages    #当前页数据也可以获取总页数
    # print(pageallnum)
    # print(pdata)
    context = {'db':pdata,'pagelist':pagelist,'num':pageallnum}


    return render(request,'admin/user/list.html',context)

def uedit(request,uid):
    ob = Users.objects.get(id=uid)
    print(ob.id)

    return render(request,'admin/user/edit.html',{'ob':ob})
    # return  HttpResponse('ll')

def usave(request):
    try:
    #获取数据对象
        ob = Users.objects.get(id=request.POST.get('id'))
        print(request.POST)
        #修改常规数据
        ob.username = request.POST.get('username')
        ob.email = request.POST.get('email')
        ob.phone = request.POST.get('phone')
        ob.sex = request.POST.get('sex')
        ob.age = request.POST.get('age')

        #判断是否有上传突破,有上传执行上传替换.
        myfile = request.FILES.get('pic')
        if myfile:
            newurl = upload.uploadimg(myfile)
            print(newurl)
            # os.remove('.'+ob.picurl)
            ob.picurl = newurl
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="/admin/user/list"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");location.href="/admin/user/edit/'+str(ob.id)+'"</script>')

def udel(request,uid):
    try:
        # print(uid)
        ob = Users.objects.get(id=uid)
        ob.status = 3
        ob.save()
        # os.remove('.'+ob.picurl)
        return HttpResponse('<script>alert("删除成功");location.href="/admin/user/list"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="/admin/user/list"</script>')

#用户状态ajax接收
def ustatus(request):
    refer = request.META['HTTP_REFERER']
    print(refer)
    ob = Users.objects.get(id=request.GET['uid'])
    ob.status = request.GET['status']
    ob.save()
    return HttpResponse('')



# 这里放上验证码:
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = '0123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')



# ajax get数据库存放的request.session['verifycode']

def vcodeajax(request):
    res = request.session['verifycode']
    print(res)
    return JsonResponse(res,safe=False)